package com.mlkj.ytdc.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

// app变动广播, 用于app被替换时重新启动新安装的app
public class AppChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        String packageName = intent.getData().getSchemeSpecificPart();
        Log.d("an-log", "onReceive: " + action + " packageName: " + packageName);
        if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
            Toast.makeText(context, packageName + "应用程序已安装", Toast.LENGTH_SHORT).show();
        } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
            Toast.makeText(context, packageName + "应用程序已升级", Toast.LENGTH_SHORT).show();

            // 这里自动重启app
            if (packageName.equals(context.getPackageName())) {
                Intent intentToStart = context.getPackageManager().getLaunchIntentForPackage(packageName);
                context.startActivity(intentToStart);
            }
        } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
            Toast.makeText(context, packageName + "应用程序已被卸载", Toast.LENGTH_SHORT).show();
        }
    }
}
